//
//  AppDelegate.m
//  XHStringPages
//
//  Created by 曾 宪华 on 13-12-20.
//  Copyright (c) 2013年 曾宪华 开发团队(http://iyilunba.com ) 本人QQ:543413507. All rights reserved.
//

#import "AppDelegate.h"
#import "NSString+XHStringPages.h"

@interface AppDelegate () {
    UIScrollView *scrollView;
    NSArray *ranges;
}

@end
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor colorWithWhite:0.498 alpha:1.000];
    
    UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicatorView.center = self.window.center;
    [activityIndicatorView startAnimating];
    [self.window addSubview:activityIndicatorView];
    UILabel *tipsLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 130, 35)];
    tipsLabel.text = @"加载数据中";
    tipsLabel.textColor = [UIColor whiteColor];
    tipsLabel.backgroundColor = [UIColor clearColor];
    tipsLabel.textAlignment = NSTextAlignmentCenter;
    tipsLabel.center = CGPointMake(activityIndicatorView.center.x, activityIndicatorView.center.y + CGRectGetHeight(activityIndicatorView.frame) / 2.0 + CGRectGetHeight(tipsLabel.frame) / 2.0);
    [self.window addSubview:tipsLabel];
    
    dispatch_async(dispatch_queue_create("Load string", NULL), ^{
        NSString *resource = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"resource" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];
        ranges = [resource getPagesOfString:resource
                                   withFont:[UIFont systemFontOfSize:15]
                                     inRect:self.window.bounds];
        dispatch_async(dispatch_get_main_queue(), ^{
            [tipsLabel removeFromSuperview];
            
            [activityIndicatorView stopAnimating];
            [activityIndicatorView removeFromSuperview];
            
            scrollView = [[UIScrollView alloc] initWithFrame:self.window.bounds];
            scrollView.alpha = 0.;
            scrollView.pagingEnabled = YES;
            
#warning Bug 由于没有重用每一页的控件，所以导致内存警告而crash了，所以需要找一个做电子书的控件，这里就不提供了，在模拟器是没有问题的，但是在真机会crash
            for (NSValue *rangeValue in ranges) {
                NSInteger index = [ranges indexOfObject:rangeValue];
                NSRange stringRange = [rangeValue rangeValue];
                NSString *string = [resource substringWithRange:stringRange];
                UILabel *pageContentLabel = [[UILabel alloc] initWithFrame:CGRectMake(index * CGRectGetWidth(self.window.frame), 0, CGRectGetWidth(self.window.frame), CGRectGetHeight(self.window.frame))];
                pageContentLabel.font = [UIFont systemFontOfSize:15];
                pageContentLabel.lineBreakMode = NSLineBreakByCharWrapping;
                pageContentLabel.numberOfLines = 0;
                pageContentLabel.backgroundColor = [UIColor whiteColor];
                pageContentLabel.textColor = [UIColor blackColor];
                pageContentLabel.text = string;
                [scrollView addSubview:pageContentLabel];
            }
            [scrollView setContentSize:CGSizeMake(ranges.count * CGRectGetWidth(self.window.frame), 0)];
            
            UIButton *scrollTopButton = [UIButton buttonWithType:UIButtonTypeCustom];
            scrollTopButton.tag = 1;
            scrollTopButton.alpha = 0.;
            [scrollTopButton setTitle:[NSString stringWithFormat:@"scrollTo 1 page"] forState:UIControlStateNormal];
            [scrollTopButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [scrollTopButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
            scrollTopButton.frame = CGRectMake(0, CGRectGetHeight(self.window.frame) - 40, 160, 40);
            
            UIButton *scrollBottomButton = [UIButton buttonWithType:UIButtonTypeCustom];
            scrollBottomButton.tag = 2;
            scrollBottomButton.alpha = 0.;
            [scrollBottomButton setTitle:[NSString stringWithFormat:@"scrollTo %d page", ranges.count] forState:UIControlStateNormal];
            [scrollBottomButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [scrollBottomButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
            scrollBottomButton.frame = CGRectMake(CGRectGetWidth(self.window.frame) - 160, CGRectGetHeight(self.window.frame) - 40, 160, 40);
            
            [self.window addSubview:scrollView];
            [self.window addSubview:scrollBottomButton];
            [self.window addSubview:scrollTopButton];
            
            [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                scrollTopButton.alpha = 1.;
                scrollBottomButton.alpha = 1.;
                scrollView.alpha = 1.;
            } completion:NULL];
            
        });
    });

    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)buttonClicked:(UIButton *)sender {
    NSInteger tag = sender.tag;
    if (tag == 1) {
        [scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    } else {
        [scrollView setContentOffset:CGPointMake((ranges.count - 1) * CGRectGetWidth(self.window.frame), 0) animated:YES];
    }
    
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
